package spring.cloud.tasks.tasks_manager.tasks_manager.task_item_allot.task;

import lombok.extern.slf4j.Slf4j;
import spring.cloud.tasks.tasks_manager.tasks_manager.node.Node;
import spring.cloud.tasks.tasks_manager.tasks_manager.service.AllotTaskItemService;
import spring.cloud.tasks.tasks_manager.tasks_manager.task_item_allot.TaskItemAllotTask;
import spring.cloud.tasks.tasks_manager.tasks_manager.task_item_allot.executor.Executor;

import java.util.List;

/**
 * 作业重排，移除所有executor的该作业shard，重新获取该作业的shards，finally删除forceShard结点
 */
@Slf4j
public class TaskExecuteForceTaskItemAllotTask extends TaskItemAllotTask {
    private final String taskId;

    public TaskExecuteForceTaskItemAllotTask(AllotTaskItemService allotTaskItemService, String taskId) {
        super(allotTaskItemService);
        this.taskId = taskId;
    }

    @Override
    protected void logStartInfo() {
        log.info("Execute the {} with {} forceShard", this.getClass().getSimpleName(), taskId);
    }

    @Override
    public void run() {
        try {
            super.run();
        } finally {
            deleteForceShardNode();
        }
    }

    private void deleteForceShardNode() {
        try {
            String taskConfigForceShardNodePath = Node.getTaskConfigForceShardNodePath(taskId);
            if (curatorFramework.checkExists().forPath(taskConfigForceShardNodePath) != null) {
                curatorFramework.delete().forPath(taskConfigForceShardNodePath);
            }
        } catch (Throwable t) {
            log.error("delete forceShard node error", t);
        }
    }

    @Override
    protected boolean pick(List<String> taskIdList,//
                           List<String> enableTaskIdList,//
                           List<TaskItem> taskItemList,//
                           List<Executor> onlineExecutorList,//
                           List<Executor> onlineOwnTrafficExecutorList) throws Exception {
        //先移除清理
        removeTaskItemList(onlineOwnTrafficExecutorList, taskId);
        //获取支持该task的Executor
        refreshExecutorTaskIdList(onlineExecutorList, taskId);
        //如果该作业是启用状态，重新创建
        if (enableTaskIdList.contains(taskId)) {
            taskItemList.addAll(createTaskItemList(taskId));
        }

        return true;
    }
}
